package com.yanqu.road.server.manager.activity.xingyou.inter.grid;

import com.yanqu.road.entity.activity.youxing.*;
import com.yanqu.road.entity.activity.youxing.config.XingYouShanShuiGridInfo;
import com.yanqu.road.entity.log.cross.xingyou.LogCrossXingYouBattle;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.helper.RandomWeightConfigHelper;
import com.yanqu.road.pb.activity.XingYouShanShuiProto;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeam;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeamMgr;
import com.yanqu.road.server.manager.activity.xingyou.ConfirmHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.CrossXingYouActivity;
import com.yanqu.road.server.manager.activity.xingyou.DiceHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.inter.GridHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.inter.IXingYouGridHandler;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 妈祖
 */
public class MaZuGridHandler implements IXingYouGridHandler {

    @Override
    public void handle(XingYouShanShuiGridInfo gridInfo, int pos, int gridId, int endPos, boolean fly, DiceHandleResult result) {
        //是否停留
        boolean stop = pos == endPos;
        if(!stop){
            return;
        }

        XingYouShanShuiProto.ShanShuiEventInfo.Builder builder = XingYouShanShuiProto.ShanShuiEventInfo.newBuilder();
        builder.setPosition(pos);
        builder.setGridId(gridId);

        Property property = new Property();

        Property fixedReward = result.getActivity().getGridInfoFixedReward(result.getUserData(), gridInfo, true);
        property.addProperty(fixedReward);
        builder.setFixedReward(PropertyHelper.parsePropertyToString(fixedReward));

        builder.setAward(PropertyHelper.parsePropertyToString(property));

        GridHandleResult gridHandleResult = new GridHandleResult();
        ShanShuiGridParam gridParam = new ShanShuiGridParam(gridId, pos, false, result.getUserData().isDrift());
        gridHandleResult.setGridParam(gridParam);
        gridHandleResult.setBuilder(builder);
        result.getGridHandleResultList().add(gridHandleResult);

        CrossXingYouActivity activity = result.getActivity();
        CrossXingYouShanShuiUserData userData = result.getUserData();
        if(!result.getUserData().isDrift()){
            //是否有回血
            CrossXingYouShanShuiData shanShuiData = activity.getShanShuiData();
            if(shanShuiData.getUserId() > 0){
//                   long add = 0;
//                   long targetUserId;
//                   String name = "";
//                   int roleId;
//                   synchronized (activity.getLock()){
//                       CrossXingYouShanShuiUserData data = activity.getUserData(shanShuiData.getUserId());
//                       targetUserId = shanShuiData.getUserId();
//                       UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(targetUserId);
//                       roleId = data.getRoleId();
//                       if(userBaseInfo != null){
//                           name = userBaseInfo.getNickName();
//                       }
//                       if(data.getTeamId() == userData.getTeamId()){
//                           if(shanShuiData.getHp() < shanShuiData.getTotalHp()){
//                               Integer addition = gridInfo.getParam().get(3);
//                               add = BigDecimal.valueOf(shanShuiData.getTotalHp()).multiply(BigDecimal.valueOf(addition)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
//                               add = Math.max(add, shanShuiData.getTotalHp() - shanShuiData.getHp());
//                               shanShuiData.setHp(shanShuiData.getHp() + add);
//                           }
//                       }
//                   }
//                   if(add > 0){
//                       CrossXingYouShanShuiTeamActionLogData logData = activity.createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_FERRY_TERMINAL, "",
//                               Arrays.asList(String.valueOf(userData.getRoleId()), name, String.valueOf(roleId), String.valueOf(add)));
//                       activity.addCrossXingYouShanShuiTeamActionLogData(logData);
//                   }
            }
        }
    }

    @Override
    public void confirm(XingYouShanShuiGridInfo gridInfo, CrossXingYouShanShuiUserData userData, ConfirmHandleResult handleResult, long select, boolean isDrift) {

        CrossXingYouActivity activity = handleResult.getActivity();

        synchronized (handleResult.getActivity().getLock()){

            if(select != activity.getShanShuiData().getUserId()){
                handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_INFO_OUT_TIME);
                return;
            }

            XingYouShanShuiProto.ShanShuiConfirmEventRsp.Builder rsp = handleResult.getBuilder();

            ShanShuiGridParam gridParam = userData.getGridParam();
            if(userData.isDrift()){
                gridParam = userData.getDriftGridParam();
            }
            if(gridParam.isHandled() || gridParam.getId() != 15){
                handleResult.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
                return;
            }

            CrossXingYouShanShuiData shanShuiData = activity.getShanShuiData();
            List<ShanShuiBeauty> beautyList = shanShuiData.getBeautyList();
            long oldHp = shanShuiData.getHp();
            long oldUserId = shanShuiData.getUserId();
            if(oldUserId > 0) {
                CrossXingYouShanShuiUserData oldUserData = activity.getUserData(oldUserId);
                if(oldUserData.getTeamId() == userData.getTeamId()){
                    //判断是否是恢复血量
                    long add = 0;
                    long targetUserId;
                    String name = "";
                    int roleId;
                    CrossXingYouShanShuiUserData data = activity.getUserData(shanShuiData.getUserId());
                    targetUserId = shanShuiData.getUserId();
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(targetUserId);
                    roleId = data.getRoleId();
                    if(userBaseInfo != null){
                        name = userBaseInfo.getNickName();
                    }
                    if(data.getTeamId() == userData.getTeamId()){
                        if(shanShuiData.getHp() < shanShuiData.getTotalHp()){
                            Integer addition = gridInfo.getParam().get(3);
                            add = BigDecimal.valueOf(shanShuiData.getTotalHp()).multiply(BigDecimal.valueOf(addition)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
                            add = Math.min(add, shanShuiData.getTotalHp() - shanShuiData.getHp());
                            shanShuiData.setHp(shanShuiData.getHp() + add);
                        }
                    }
                    if(add > 0){
                        CrossXingYouShanShuiTeamActionLogData logData = activity.createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_MA_ZU_HP_ADD, "",
                                Arrays.asList(String.valueOf(userData.getRoleId()), name, String.valueOf(roleId), String.valueOf(gridInfo.getParam().get(3))));
                        handleResult.getActionLogDataList().add(logData);

                        //回血日志
                        LogCrossXingYouBattle logBattle = new LogCrossXingYouBattle(userData.getActivityId(), userData.getUserId(), userData.getTeamId(), gridInfo.getId(),gridParam.getMapIndex(),
                                userData.getMapTeamId(), oldUserId, userData.getTeamId(), 3, 0, add, shanShuiData.getHp(), 0, 0, 0, "");
                        handleResult.getAutoLogList().add(logBattle);
                    }
                    gridParam.setHandled(true);
                    gridParam.setEventParam(2);

                    //同步给在线的玩家
                    shanShuiData.isNeedSync().set(true);
                    return;
                }
            }

            //判断CD
            int currentSecond = DateHelper.getCurrentSecond();
            if(shanShuiData.getMaZuChangeTime() > 0 && shanShuiData.getMaZuChangeTime() + handleResult.getActivity().getConfig().getSHUISHUI_MAZU_PROTECT_TIME() >= currentSecond){
                handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_MAZU_PROTECT_CD);
                return;
            }

            XingYouShanShuiProto.ShanShuiBattleRecordMsg.Builder battleBuilder = activity.battle(userData.getUserId(), shanShuiData.getUserId(), beautyList, (int)shanShuiData.getHp());

            //随机奖励
            Property property = PropertyHelper.parseStringToProperty(gridInfo.getReward1());

            handleResult.getBuilder().setBaseReward(PropertyHelper.parsePropertyToString(property));

            handleResult.getActivity().calRewardBuff(userData, property, false, 0);

            if(!battleBuilder.getIsWin()){
                shanShuiData.setHp(battleBuilder.getEnemyHp());

                //失败日志
                LogCrossXingYouBattle logBattle = new LogCrossXingYouBattle(userData.getActivityId(), userData.getUserId(), userData.getTeamId(), gridInfo.getId(),gridParam.getMapIndex(),
                        userData.getMapTeamId(), oldUserId, userData.getTeamId(), 4, 0, oldHp - shanShuiData.getHp(), shanShuiData.getHp(),
                        0, property.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_SILVER_COIN_ID()).intValue(),
                        property.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID()).intValue(), PropertyHelper.parsePropertyToString(property));
                handleResult.getAutoLogList().add(logBattle);

            }else {
                //替换
                shanShuiData.setUserId(userData.getUserId());
                List<ShanShuiBeauty> list = new ArrayList<>();
                int total = 0;
                for (ShanShuiBeauty beauty : userData.getBeautyList()) {
                    list.add(beauty.copy());
                    total += beauty.getTotal();
                }
                shanShuiData.setBeautyList(list);
                shanShuiData.setTotalHp(total);
                shanShuiData.setHp(total);
                shanShuiData.setMaZuChangeTime(currentSecond);

                //日志
                //失去
                if(oldUserId > 0){
                    CrossXingYouShanShuiUserData oldUserData = activity.getUserData(oldUserId);

                    CommonTeam team = CommonTeamMgr.getTeam(userData.getActivityId(), 0, userData.getTeamId());
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userData.getUserId());
                    if(team != null) {
                        CrossXingYouShanShuiTeamActionLogData logData = activity.createActionLogData(oldUserData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_SWALLOW_RETURN_LIGHTHOUSE_FAIL,
                                "", Arrays.asList(String.valueOf(userData.getRoleId()), team.getTeamName(), userBaseInfo == null ? "" : userBaseInfo.getNickName()));
                        handleResult.getActionLogDataList().add(logData);
                    }
                }else {

                }
                //进驻
                if(oldUserId > 0){
                    CrossXingYouShanShuiUserData oldUserData = activity.getUserData(oldUserId);
                    CommonTeam oldTeam = CommonTeamMgr.getTeam(oldUserData.getActivityId(), 0, oldUserData.getTeamId());
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(oldUserId);
                    if(oldTeam != null) {
                        CrossXingYouShanShuiTeamActionLogData logData = activity.createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_SWALLOW_RETURN_LIGHTHOUSE,
                                PropertyHelper.parsePropertyToString(property), Arrays.asList(String.valueOf(userData.getRoleId()), oldTeam.getTeamName(), userBaseInfo == null ? "" : userBaseInfo.getNickName()));
                        handleResult.getActionLogDataList().add(logData);

                        LogCrossXingYouBattle logBattle = new LogCrossXingYouBattle(userData.getActivityId(), userData.getUserId(), userData.getTeamId(), gridInfo.getId(),gridParam.getMapIndex(),
                                userData.getMapTeamId(), oldUserId, userData.getTeamId(), 4, 0, oldHp - battleBuilder.getEnemyHp(), battleBuilder.getEnemyHp(),
                                1, property.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_SILVER_COIN_ID()).intValue(),
                                property.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID()).intValue(), PropertyHelper.parsePropertyToString(property));
                        handleResult.getAutoLogList().add(logBattle);
                    }
                }else {
                    CrossXingYouShanShuiTeamActionLogData logData = activity.createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_SWALLOW_RETURN_LIGHTHOUSE,
                            //npc 客户端解析
                            PropertyHelper.parsePropertyToString(property), Arrays.asList(String.valueOf(userData.getRoleId()), "npc"));
                    handleResult.getActionLogDataList().add(logData);

                    LogCrossXingYouBattle logBattle = new LogCrossXingYouBattle(userData.getActivityId(), userData.getUserId(), userData.getTeamId(), gridInfo.getId(),gridParam.getMapIndex(),
                            userData.getMapTeamId(), 0, 0, 4, 0, oldHp - battleBuilder.getEnemyHp(), battleBuilder.getEnemyHp(),
                            1, property.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_SILVER_COIN_ID()).intValue(),
                            property.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID()).intValue(), PropertyHelper.parsePropertyToString(property));
                    handleResult.getAutoLogList().add(logBattle);
                }
            }

            handleResult.getReward().addProperty(property);

            //同步给在线的玩家
            shanShuiData.isNeedSync().set(true);

            rsp.setBattleRecord(battleBuilder);
            rsp.setRet(0);
            rsp.setIsWin(battleBuilder.getIsWin());
            rsp.setHpMax(shanShuiData.getTotalHp());
            rsp.setHpPercent(shanShuiData.getHp());

            gridParam.setHandled(true);
            gridParam.setEventParam(1);
        }
    }
}
